package org.example.reggie.filter;

import com.alibaba.fastjson.JSON;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.reggie.result.ResultData;
import org.example.reggie.utils.ThreadLocalUtil;
import org.springframework.util.AntPathMatcher;

import java.io.IOException;

/**
 * 过滤器：检查是否登录
 * 两种方式：
 * 一、@WebFilter注解方式 ，这种方式需要在启动类添加@ServletComponentScan，它负责扫描@WebServlet、@WebFilter、@WebListener这三个注解
 * 二、@Bean注解方式,不要加注解@WebFilter,但是需要新建配置类WebConfig.java，配置bean，并加上注解@Configuration
 */
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    //路径匹配通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request  = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI();
        String [] urls = new String[]{
                "/employee/login",
                "/employee/login",
                "/backend/**",
                "/front/**",
                "/user/sendMsg",
                "/user/login",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };

        boolean flag = check(urls,requestURI);
        //直接放行
        if(flag){
            filterChain.doFilter(request,response);
            return;
        }
        //判断登录状态，如果已经登录，直接放行
        if(null != request.getSession().getAttribute("employee") && ThreadLocalUtil.getMap().size() > 0){
            filterChain.doFilter(request,response);
            return;
        }
        //未登录时，直接使用输出流的方式向客户端响应数据,在前端的的统一响应中做处理判断
        response.getWriter().write(JSON.toJSONString(ResultData.error("NOTLOGIN")));
        return;
    }

    /**
     * 检查路径是否是属于放行的那种
     * @param urls
     * @param requestUrl
     * @return
     */
    private boolean check (String[] urls,String requestUrl){
        boolean result = false;
        //遍历的同时调用PATH_MATCHER来对路径进行匹配
        for (String currUrl : urls) {
            result = PATH_MATCHER.match(currUrl, requestUrl);
            if (result){
                //匹配到了可以放行的路径，直接放行
                return true;
            }
        }
        //否则就是没有匹配到，不予放行
        return result;

    }
}
